package self.hoy.demo.cloud.order.lb;


import org.springframework.cloud.client.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 三共小不
 * @date 2020/6/2
 */
@Component
public class DemoLoadBalancer implements LoadBalancer {

    /**
     * 用于记录调用provider的次数
     */
    private AtomicInteger atomicInteger = new AtomicInteger(0);

    public int get() {
        return atomicInteger.get();
    }

    /**
     * 对这个方法的并发安全调试在 IncreaseComparator.java 中
     * @return
     */
    public final int getAndIncrement() {
        int current, next;
        do {
            current = atomicInteger.get();
            next = current >= Integer.MAX_VALUE ? 0 : current + 1;
        } while (!this.atomicInteger.compareAndSet(current, next));
        return next;
    }

    @Override
    public ServiceInstance instances(List<ServiceInstance> si) {
        return si == null || si.isEmpty() ?
                null :
                si.get( getAndIncrement() % si.size() );
    }

    public static void main(String[] args) {
        DemoLoadBalancer a = new DemoLoadBalancer();
        a.atomicInteger = new AtomicInteger(Integer.MAX_VALUE);
        System.out.println(a.getAndIncrement());
//        System.out.println(Integer.MAX_VALUE + 1);
    }
}
